package com.ruoyi.web.controller.utilcontroller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.newAdd.aliyun.oss.FileService;
import com.ruoyi.common.newAdd.returnResult.Data;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @Value("${uploadDir}")
    private String uploadDir;

    /**
     * 上传凭证
     * @param file
     * @return
     * @throws RuntimeException
     */
    @PostMapping("/upload/voucher")
    public Res voucher(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {
        if (file.isEmpty()) {
            return Res.errorShowMsg("文件为空!");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = uploadDir;
        String path = filePath +"temp"+suffixName;
        File dest = new File(path);
        String pth = "";
        try {
            file.transferTo(dest);
            //文件存储在名为voucher的文件夹里
            pth = fileService.toOSS(suffixName,"voucher",path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Res.okShowMsg("图片上传成功！").put("data",Data.ok().put("src",pth));
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload/picture")
    public AjaxResult uploadPicture(MultipartFile file) throws Exception
    {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = uploadDir;
        String path = filePath +"temp"+suffixName;
        File dest = new File(path);
        String pth = "";
        try {
            file.transferTo(dest);
            //文件存储在名为picture的文件夹里
            pth = fileService.toOSS(suffixName,"picture",path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", pth);
        ajax.put("fileName", pth);
//        ajax.put("newFileName", FileUtils.getName(fileName));
//        ajax.put("originalFilename", file.getOriginalFilename());
        return ajax;
    }
}
